<template>
  <view class="container">
    <view v-if="user">
      <view style="text-align:center;margin-bottom:24px;">
        <image :src="user.avatar || defaultAvatar" style="width:80px;height:80px;border-radius:50%;background:#eee;" />
        <view style="margin-top:8px;font-size:18px;">{{ user.nickname || user.username }}</view>
        <view style="color:#888;font-size:14px;">{{ user.phone }}</view>
      </view>
      <view class="btn-primary" @click="logout">退出登录</view>
    </view>
    <view v-else>
      <view style="text-align:center;margin:40px 0;">请先登录</view>
      <view class="btn-primary" @click="goLogin">去登录</view>
    </view>
  </view>
</template>

<script>
import { getUserInfo } from '../../api/user.js'
import { mapState, mapMutations } from 'vuex'
export default {
  data() {
    return {
      defaultAvatar: 'https://cdn.jsdelivr.net/gh/stevenjoezhang/live2d-widget@latest/waifu.png'
    }
  },
  computed: {
    ...mapState(['user', 'token'])
  },
  onShow() {
    if (this.token) {
      getUserInfo().then(result => {
        if (result.code === 200) {
          this.setUser(result.data)
        } else {
          console.error('获取用户信息失败:', result.message)
        }
      }).catch(err => {
        console.error('获取用户信息失败:', err)
      })
    }
  },
  methods: {
    ...mapMutations(['logout', 'setUser']),
    goLogin() {
      uni.redirectTo({ url: '/pages/login/login' })
    }
  }
}
</script>

<style scoped>
.container {
  padding: 40px 24px;
}
</style>
